package com.example.kafka.kerberos.controller;

import com.example.kafka.kerberos.common.Krb5Utils;
import com.example.kafka.kerberos.dao.Krb5KeyTabRepository;
import com.example.kafka.kerberos.pojo.AuthFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author stone
 * @version $1.0
 * @date 2020/9/21 09:59:22
 */
@RestController
public class Krb5Controller {

    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    public static final int EOF = -1;

    @Resource
    private Krb5KeyTabRepository krb5KeyTabRepository;

    @PostMapping("/upload")
    public String upload(MultipartFile keyTabFile) throws Exception {
        byte[] bytes = keyTabFile.getBytes();

        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encode = encoder.encode(bytes);
        String encodeStr = new String(encode, StandardCharsets.UTF_8);

        String referId = Krb5Utils.uuidKey();
        AuthFile authFile = new AuthFile();
        authFile.setReferId(referId);
        authFile.setContent(encodeStr);
        krb5KeyTabRepository.save(authFile);
        return authFile.getReferId();
    }

    @GetMapping("/load")
    public String load(@RequestParam String referId) throws Exception {
        AuthFile authFile = krb5KeyTabRepository.findByReferId(referId);
        String content = authFile.getContent();

        byte[] encodeStrBytes = content.getBytes(StandardCharsets.UTF_8);
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decode = decoder.decode(encodeStrBytes);


        String tmpFileName = "/tmp/" + Krb5Utils.tmpFileName();
        File tmpFile = new File(tmpFileName);
        FileUtils.writeByteArrayToFile(tmpFile, decode);
        return tmpFileName;
    }
}
